package com.jiepos.mpos.core.intercept;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jiepos.mpos.biz.user.service.UserService;
import com.jiepos.mpos.common.constant.ExceptionConstant;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.core.util.StringUtils;

@Component
public class UserInterceptor extends HandlerInterceptorAdapter{
	public final Logger log = LoggerFactory.getLogger(getClass());
	/** 主页面访问路径*/
	private static final String MAIN_URL = "userlogin/main.do";
	/** 检测session*/
	private static final String CHECK_SESSION = "userlogin/checksession.do";
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String postUri = request.getRequestURI();		
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute(SystemConstant.SESSION_USER_UUID);
		//  保存后台操作日志数据 
		log.debug("preHandle:{} userId:{} ip:{} ",postUri,userId,this.getIpAddr(request));
		// 未登录，跳转登陆页面
		if(StringUtils.isBlank(userId)){
			String contextPath = request.getContextPath();
			if(StringUtils.isBlank(request.getContextPath())){
				contextPath = "/";
			}
			response.sendRedirect(contextPath);
			return false;
		}
		// 登陆之后操作，验证用户是否依然存在或者可以操作
//		if(!userService.checkLoginUser(userId)){
//			session.invalidate();
//			response.sendRedirect(request.getContextPath());
//			return false;
//		}
		// 验证请求url
		List<String> urls = (List<String>) session.getAttribute(SystemConstant.SESSION_AUTH_LIST);
		if(urls == null || urls.isEmpty()){
			return false;
		}
		String requestUrl = request.getRequestURI();
		requestUrl = requestUrl.substring(request.getContextPath().length() + 1);
		boolean isAuth = false;
		for(String url : urls){
			if(url.contains(requestUrl)){
				isAuth = true;
				break;
			}
		}
		/*访问主页面或者检测session放行*/
		if(MAIN_URL.equals(requestUrl) || CHECK_SESSION.equals(requestUrl)){
			isAuth = true;
		}
		if(!isAuth){
			createMsg(request, response);
		}
		return isAuth;
	}
	
	@Override
	public void postHandle(
			HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
			throws Exception {
	}
	
	@Override
	public void afterCompletion(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
	
	@Override
	public void afterConcurrentHandlingStarted(
			HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
	}

	private void createMsg(HttpServletRequest request, HttpServletResponse response){
		try {
			String contentType = request.getHeader("Accept");
			String warnMsg = ExceptionConstant.USER_HAVE_NO_AUTH.getMessage();
			PrintWriter pw = response.getWriter();
			pw.flush();
			if(contentType.contains("json")){
				pw.write(warnMsg);
			}else{
				pw.write("<script type='text/javascript'>alert('"+warnMsg+"')</script>");
			}
			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	  /**
     * 通过HttpServletRequest返回IP地址
     * @param request HttpServletRequest
     * @return ip String
     * @throws Exception
     */
    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
